package com.furyspring.service.impl;

import com.furyspring.annotation.Autowired;
import com.furyspring.annotation.Service;
import com.furyspring.annotation.Transactional;
import com.furyspring.dao.AccountDao;
import com.furyspring.pojo.Account;
import com.furyspring.service.TransferService;

/**
 * @author 应癫
 */
@Transactional
@Service("furySpringService")
public class TransferServiceImpl implements TransferService {

    //private AccountDao accountDao = new JdbcAccountDaoImpl();
    // private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");

    // 最佳状态
    @Autowired
    private AccountDao accountDao;

    // 构造函数传值/set方法传值
//    public void setAccountDao(AccountDao accountDao) {
//        this.accountDao = accountDao;
//    }


    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setBalance(from.getBalance() - money);
        to.setBalance(to.getBalance() + money);

        accountDao.updateAccountByCardNo(from);
        checkFromBalance(from.getBalance(), money);
        accountDao.updateAccountByCardNo(to);
    }

    private void checkFromBalance(Integer balance, int money) {
        if (balance < money) {
            throw new IllegalStateException("余额不足！");
        }
    }
}
